package network;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.JComboBox;

import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;

import javax.swing.JTextPane;

import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.RowSpec;
import com.jgoodies.forms.factories.FormFactory;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;

import net.miginfocom.swing.MigLayout;

import java.awt.GridLayout;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import javax.swing.JLabel;
import javax.swing.DefaultComboBoxModel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import javax.swing.JTextField;

import java.awt.Dimension;

public class MultiChatServer extends JFrame implements Runnable {

	private JPanel contentPane;
	private JPanel panel;
	private JPanel panel_1;
	private JPanel panel_2;
	private JScrollPane scrollPane_1;
	JList list;
	private JComboBox comboBox;
	private JButton btnOpen;
	private JScrollPane scrollPane;
	private JButton btnRead;
	private JButton btnExcel;
	private JButton btnBackup;
	private JButton btnClose;
	private JComboBox comboBox_1;
	private JTextPane result;
	private JLabel label;
	private JLabel label_1;
	private JLabel label_2;
	private JLabel label_3;
	InetAddress ia;
	int port = 4444;
	ServerSocket server;
	Socket client;
	MultiChatServerThread mcst; //접속된 클라이언트 당 1개 발생
	StringBuilder data = new StringBuilder();
	HashMap clients = new HashMap();
	private JPanel panel_3;
	private JTextField textField;
	private JButton btnNewButton;
	private JTextField textField_1;

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MultiChatServer frame = new MultiChatServer();
					frame.setVisible(true);
					
					MultiChatClient c = new MultiChatClient();
					c.userID.setText("최규석");
					c.textField.setText("최규석....");
					c.setLocation(frame.getX()+frame.getWidth(), frame.getY());
					c.setVisible(true);
					
					MultiChatClient c2 = new MultiChatClient();
					c2.userID.setText("장");
					c2.textField.setText("장.....");
					c2.setLocation(c.getX(), c.getY()+c.getHeight());
					c2.setVisible(true);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public MultiChatServer() {
		try {
			ia = InetAddress.getLocalHost();
			setTitle(ia + " || 포트 : " + port);
		} catch (Exception e) {
			e.printStackTrace();
		}
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(0, 0, 800, 700);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getPanel(), BorderLayout.CENTER);
		contentPane.add(getPanel_1(), BorderLayout.WEST);
		contentPane.add(getPanel_2(), BorderLayout.EAST);
		contentPane.add(getPanel_3(), BorderLayout.SOUTH);
	}

	@Override
	public void run() {
		try {
			server = new ServerSocket(port); // 자기가 소켓 열고
			dataSet("<div style='border:1px solid #ff0000;background-color:#ffdddd'>"  
			        + "<font color='blue'>서버가 시작되었습니다.</font>");
			SimpleDateFormat sdf = 
					new SimpleDateFormat("서버 시작 시간 :  yyyy년 MM월 dd일 hh시 mm분 ss초");
			String str = sdf.format(new Date())+"\n";
			dataSet(str);
			dataSet("</div>");
			
			while (true) {
				client = server.accept(); //-> 1:1이 아니므로 계속 접속대기 해야됨
				System.out.println("클라이언트 접속대기......");
				System.out.println(client); //Socket[addr=/192.168.10.101,port=52215,localport=4444]
				mcst = new MultiChatServerThread(this, client); //자기자신과 소켓을 매개변수로 mcst생성
//				mcst.start(); // 이거 때문에 중복 떠서 안됐었음
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	void dataSet(String string) {
		data.append(string + "<br/>");
		result.setText(data.toString());
		result.setCaretPosition(result.getDocument().getLength());
	}
	
	private JPanel getPanel() {
		if (panel == null) {
			panel = new JPanel();
			panel.setLayout(new BorderLayout(0, 0));
			panel.add(getScrollPane(), BorderLayout.CENTER);
		}
		return panel;
	}
	private JPanel getPanel_1() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getScrollPane_1_1(), BorderLayout.CENTER);
		}
		return panel_1;
	}
	private JPanel getPanel_2() {
		if (panel_2 == null) {
			panel_2 = new JPanel();
			panel_2.setLayout(new GridLayout(0, 1, 0, 0));
			panel_2.add(getBtnOpen());
			panel_2.add(getLabel());
			panel_2.add(getBtnBackup());
			panel_2.add(getLabel_1());
			panel_2.add(getBtnRead());
			panel_2.add(getLabel_2());
			panel_2.add(getBtnExcel());
			panel_2.add(getLabel_3());
			panel_2.add(getBtnClose());
		}
		return panel_2;
	}
	private JScrollPane getScrollPane_1_1() {
		if (scrollPane_1 == null) {
			scrollPane_1 = new JScrollPane();
			scrollPane_1.setMinimumSize(new Dimension(30, 23));
			scrollPane_1.setViewportView(getList());
			scrollPane_1.setColumnHeaderView(getComboBox());
		}
		return scrollPane_1;
	}
	private JList getList() {
		if (list == null) {
			list = new JList();
		}
		return list;
	}
	private JComboBox getComboBox() {
		if (comboBox == null) {
			comboBox = new JComboBox();
			comboBox.setModel(new DefaultComboBoxModel(new String[] {"아이디"}));
		}
		return comboBox;
	}
	private JButton getBtnOpen() {
		if (btnOpen == null) {
			btnOpen = new JButton("개   방");
			btnOpen.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					open();
				}
			});
		}
		return btnOpen;
	}
	
	void open() {
		Thread t = new Thread(this);
		t.start();
	}
	
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setColumnHeaderView(getComboBox_1());
			scrollPane.setViewportView(getResult());
		}
		return scrollPane;
	}
	private JButton getBtnRead() {
		if (btnRead == null) {
			btnRead = new JButton("읽   기");
		}
		return btnRead;
	}
	private JButton getBtnExcel() {
		if (btnExcel == null) {
			btnExcel = new JButton("엑셀화");
		}
		return btnExcel;
	}
	private JButton getBtnBackup() {
		if (btnBackup == null) {
			btnBackup = new JButton("SQL 백업");
		}
		return btnBackup;
	}
	private JButton getBtnClose() {
		if (btnClose == null) {
			btnClose = new JButton("폐   쇄");
		}
		return btnClose;
	}
	private JComboBox getComboBox_1() {
		if (comboBox_1 == null) {
			comboBox_1 = new JComboBox();
			comboBox_1.setModel(new DefaultComboBoxModel(new String[] {"시간"}));
		}
		return comboBox_1;
	}
	private JTextPane getResult() {
		if (result == null) {
			result = new JTextPane();
			result.setContentType("text/html");
		}
		return result;
	}
	private JLabel getLabel() {
		if (label == null) {
			label = new JLabel("");
		}
		return label;
	}
	private JLabel getLabel_1() {
		if (label_1 == null) {
			label_1 = new JLabel("");
		}
		return label_1;
	}
	private JLabel getLabel_2() {
		if (label_2 == null) {
			label_2 = new JLabel("");
		}
		return label_2;
	}
	private JLabel getLabel_3() {
		if (label_3 == null) {
			label_3 = new JLabel("");
		}
		return label_3;
	}
	private JPanel getPanel_3() {
		if (panel_3 == null) {
			panel_3 = new JPanel();
			panel_3.setLayout(new BorderLayout(0, 0));
			panel_3.add(getTextField(), BorderLayout.CENTER);
			panel_3.add(getBtnNewButton(), BorderLayout.EAST);
			panel_3.add(getTextField_1(), BorderLayout.WEST);
		}
		return panel_3;
	}
	private JTextField getTextField() {
		if (textField == null) {
			textField = new JTextField();
			textField.setColumns(10);
		}
		return textField;
	}
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			btnNewButton = new JButton("서버 메시지");
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					sendMsg();
				}
			});
		}
		return btnNewButton;
	}
	
	void sendMsg() {
		SocketData sd = new SocketData("message", "server", textField.getText() ,null);
		mcst.sendMsg(sd);
		dataSet(sd);
	}
	
	private JTextField getTextField_1() {
		if (textField_1 == null) {
			textField_1 = new JTextField();
			textField_1.setText("아이디");
			textField_1.setColumns(10);
		}
		return textField_1;
	}

	public void dataSet(SocketData sdIn) {
		data.append(sdIn.getUser() + " : " + sdIn.getMessage() + "<br/>");
		result.setText(data.toString());
		
		result.setCaretPosition(result.getDocument().getLength());
	}
	
	
	
}
